//
//  ShopListViewContrller.m
//  uneed
//
//  Created by apple on 4/11/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ShopListViewContrller.h"
#import "UneedGet2Api.h"
#import "JSONKit.h"
#import "MapViewCtrl.h"

@interface ShopListViewContrller ()

- (void)startImageDownload:(NSString *)imageUrl forIndexPath:(NSIndexPath *)indexPath;

@end

@implementation ShopListViewContrller


@synthesize shopName,shopSubName,tvCell,shoplists;
@synthesize imageDownloadsInProgress,shopImage,useDarkBackground,shopClasses;
@synthesize distance;

#define DARK_BACKGROUND  [UIColor colorWithRed:151.0/255.0 green:152.0/255.0 blue:155.0/255.0 alpha:1.0]
#define LIGHT_BACKGROUND [UIColor colorWithRed:172.0/255.0 green:173.0/255.0 blue:175.0/255.0 alpha:1.0]

#define kCustomRowHeight    60.0
#define kCustomRowCount     1

- (void)dealloc
{
	[distance release];
	[shopClasses release];
	[shopImage release];
	[shoplists release];
	[shopName release];
	[shopSubName release];
    [tvCell release];	
	[imageDownloadsInProgress release];
    [super dealloc];
}

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)actShopAdd {
	//	RootGroupView *rootGroupView = [[RootGroupView alloc] initWithStyle:UITableViewStylePlain];
//	RootGroupView *rootGroupView = [[RootGroupView alloc] initWithStyle:[appDelegate getTableViewStyle]];

	ShopAddViewCtrl *shopAddViewCtrl = [[ShopAddViewCtrl alloc]init];
	shopAddViewCtrl.title = @"添加商家";
	[self.navigationController pushViewController:shopAddViewCtrl animated:YES];
	[shopAddViewCtrl release];
	//	rootGroupView.title = @"百度音乐盒";
	//	naviCtrl = [[UINavigationController alloc] initWithRootViewController:rootGroupView];
//	[rootGroupView release];
}


- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.title = @"附近商家";
	
//	UIBarButtonItem *btnShopAdd = [[UIBarButtonItem alloc] 
//									   initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(loadMusicAction)];
//	self.navigationItem.rightBarButtonItem = btnShopAdd;
//	[btnShopAdd release];
	
	self.navigationItem.rightBarButtonItem.enabled = YES;
	self.navigationItem.rightBarButtonItem.title =@"添加商家";
	self.navigationItem.rightBarButtonItem.action = @selector(actShopAdd);
	self.navigationItem.rightBarButtonItem.target = self;
	
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
	self.shopClasses = [NSMutableDictionary dictionary];
    self.tableView.rowHeight = kCustomRowHeight;

	if (shoplists==NULL) shoplists = [[NSMutableArray alloc]init];
	//    [shoplists addObjectsFromArray:[UneedGet2Api getShopListsWithLat:0 withLng:0 ]];
	[shoplists removeAllObjects];
	page = 1;
	page_isend = FALSE;
	is_loaddate = FALSE;
	[UneedGet2Api getShopListsWithLat:0 withLng:0 withPage:page withDelegate:self withIndex:0];
	
	
	//	[[RemoteImage alloc] init];
	
//    self.tableView.backgroundColor = DARK_BACKGROUND;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
	NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];

}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	int count = [shoplists count];
	
	// ff there's no data yet, return enough rows to fill the screen
    if (count == 0)
	{
        return kCustomRowCount;
    }
    return count;
	
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"ShopCellViewCtrl";
	
	static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";

	int nodeCount = [shoplists count];
	
	if (nodeCount == 0)
	{
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		if (indexPath.row == 0)
		cell.detailTextLabel.text = @"数据加载中...";
		
		return cell;
    }
	
	if (indexPath.row >= [shoplists count] -1) {
		if (!page_isend && !is_loaddate) {
			page++;
			is_loaddate = TRUE;
			[UneedGet2Api getShopListsWithLat:loc_lat*1000000 withLng:loc_lng*1000000 withPage:page withDelegate:self withIndex:0];
		}
	}
	
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {       
//        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//        [[NSBundle mainBundle] load
//        [[UINib nibWithNibName:@"ShopCellViewCtrl" bundle:nil]instantiateWithOwner:self options:nil];
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShopCellViewCtrl" owner:self options:nil];
		if ([nib count]>0)
			cell = self.tvCell;
//		self.tmpCell = nil;
        
        
    }
	
	Shop *ashop = [shopClasses objectForKey:indexPath];
	if (ashop==NULL) {    
		NSDictionary *ashopdic = [shoplists objectAtIndex:[indexPath row]];
		ashop = [[Shop alloc]init];
		ashop.name = [ashopdic objectForKey:@"name"];
		ashop.subname = [ashopdic objectForKey:@"subname"];
		ashop.thumb = [ashopdic objectForKey:@"thumb"];
		ashop.distance = [ashopdic objectForKey:@"distance"];
		ashop.description = [ashopdic objectForKey:@"description"];
		ashop.categoryname = [ashopdic objectForKey:@"categoryname"];
		ashop.map_lat = [[ashopdic objectForKey:@"map_lat"] floatValue];
		ashop.map_lng = [[ashopdic objectForKey:@"map_lng"] floatValue];
		[shopClasses setObject:ashop forKey:indexPath];
		[ashop release];
	}
    [shopName setText:ashop.name];
    [shopName sizeToFit];
    if (![ashop.subname isEqual:@""]) {
        [shopSubName setText:[NSString stringWithFormat:@"(%@)",ashop.subname]];
        [shopSubName sizeToFit];
        shopSubName.frame = CGRectMake(shopName.frame.origin.x + shopName.frame.size.width+5,shopSubName.frame.origin.y,shopSubName.frame.size.width,shopSubName.frame.size.height);
        
    } else {
        [shopSubName setText:@""];
    }//    cell.shopName.frame.origin.x + cell.shopName.frame.size.width;
	float i_distance = [ashop.distance floatValue];
	if (i_distance>=100000) {
		[distance setText:[NSString stringWithFormat:@"%.0f公里",i_distance/1000]];
	} else if (i_distance>=10000) {
			[distance setText:[NSString stringWithFormat:@"%.1f公里",i_distance/1000]];
	} else if (i_distance>=1000) {
			[distance setText:[NSString stringWithFormat:@"%.2f公里",i_distance/1000]];
	} else {
			[distance setText:[NSString stringWithFormat:@"%.0f米",i_distance]];
	} 
//	[distance setText:[NSString stringWithFormat:@"%@",ashop.distance]];
//	[distance sizeToFit];
    // Set up the cell...
	
	if (ashop.shopimg==NULL)
	{
		if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
		{
			NSString *imgUrl = ashop.thumb;
			if (![imgUrl isEqual:@""]) {
				imgUrl = [NSString stringWithFormat:@"%@%@",M_ROOT,imgUrl];
			[self startImageDownload:imgUrl forIndexPath:indexPath];
			}
		}
		// if a download is deferred or in progress, return a placeholder image
		[shopImage setImage:[UIImage imageNamed:@"Placeholder_loading.png"]];                
	}
	else
	{
		[shopImage setImage:ashop.shopimg]; 

//		cell.imageView.image = appRecord.appIcon;
	}
	
    return cell;
}


// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([shoplists count] > 0)
    {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            Shop *ashop = [shopClasses objectForKey:indexPath];
            
            if (ashop.shopimg==NULL) // avoid the app icon download if the app already has an icon
            {
                [self startImageDownload:ashop.thumb forIndexPath:indexPath];
            }
        }
    }
}

- (void)startImageDownload:(NSString *)imageUrl forIndexPath:(NSIndexPath *)indexPath
{
	IconDownloader *remoteImage = [imageDownloadsInProgress objectForKey:indexPath];
	if (remoteImage == nil) 
	{
		remoteImage = [[IconDownloader alloc] init];
		remoteImage.imageUrl = imageUrl;
		remoteImage.indexPathInTableView = indexPath;
		remoteImage.delegate = self;
		[imageDownloadsInProgress setObject:remoteImage forKey:indexPath];
		[remoteImage startDownload];
		[remoteImage release];   
	}
	
}

// called by our ImageDownloader when an icon is ready to be displayed
- (void)appImageDidLoad:(NSIndexPath *)indexPath
{
    IconDownloader *remoteImage = [imageDownloadsInProgress objectForKey:indexPath];
    if (remoteImage != nil)
    {
//        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:remoteImage.indexPathInTableView];
        
        // Display the newly loaded image
		Shop *ashop = [shopClasses objectForKey:indexPath];
		if (ashop!=NULL) {
			ashop.shopimg = remoteImage.remoteImage;
			[self.tableView reloadData];
		}
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	Shop *_ashop = [shopClasses objectForKey:indexPath];
	if (_ashop!=NULL) {
		MapViewCtrl *_mapViewCtrl = [[MapViewCtrl alloc]init];
		_mapViewCtrl.title = [NSString stringWithFormat:@"%f",[_ashop map_lat]];
		_mapViewCtrl.map_lat = [_ashop map_lat];
		_mapViewCtrl.map_lng = [_ashop map_lng];
		[self.navigationController pushViewController:_mapViewCtrl animated:YES];
		[_mapViewCtrl release];
	}	
	
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    cell.backgroundColor = ((ShopCellViewCtrl *)cell).useDarkBackground ? DARK_BACKGROUND : LIGHT_BACKGROUND;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//   if ([shoplists count]>0)
	return 73;    
}

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}


-(void)  errorCallback:(NSArray*) error {
    
}

/*数据下载完毕 */
-(void)  completedCallback:(NSArray *) data {
	if ([data count]<2) return;
	NSString *_data = [NSString stringWithFormat:@"%@",[data objectAtIndex:1]];

    NSMutableDictionary *jsondic = [_data objectFromJSONString];
	NSNumber *errCode = [jsondic objectForKey:@"errCode"];
	if ([errCode intValue]==0) {
		if ([[jsondic objectForKey:@"errMessage"] count]<20) page_isend = TRUE;
		is_loaddate = FALSE;
		[shoplists addObjectsFromArray:[jsondic objectForKey:@"errMessage"]];
		[self.tableView reloadData];
	}
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	[super locationManager:manager didUpdateToLocation:newLocation fromLocation:oldLocation];
	CLLocationCoordinate2D loc = [newLocation coordinate];
	if (fabs([newLocation coordinate].latitude -[oldLocation coordinate].latitude)>0.1 || fabs([newLocation coordinate].longitude - [oldLocation coordinate].longitude)>0.1) {
		
	[shoplists removeAllObjects];
		page=1;
		page_isend = FALSE;
	[self.tableView reloadData];
		[UneedGet2Api getShopListsWithLat:loc.latitude*1000000 withLng:loc.longitude*1000000 withPage:page withDelegate:self withIndex:0];

	}
}

@end

